package com.topisv.tms.utils.ems;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;

import com.topisv.tms.utils.ems.getExpressNo.EmsResponse;
import com.topisv.tms.utils.ems.sendPrintData.EmsPrintDataResponse;
import com.topisv.tms.utils.ems.sendPrintData.EmsXMLInfoRequest;

public class EmsUtil {
	static Logger log = LoggerFactory.getLogger(EmsUtil.class);
	
	final static String ACCOUNT = "44191841868000";
//	final static String ACCOUNT = "44190042050000";
	final static String PASSWORD = "a0a475cf454cf9a06979034098167b9e";
	
	final static String EMS_EXPRESS_URI = "http://os.ems.com.cn:8081/zkweb/bigaccount/getBigAccountDataAction.do";
	

	private static String SEND_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><XMLInfo><sysAccount>{sysAccount}</sysAccount><passWord>{passWord}</passWord><businessType>{businessType}</businessType><billNoAmount>{billNoAmount}</billNoAmount></XMLInfo>";

	public static EmsResponse getExpressNo(String billNoAmount,String account,String password,String url) throws Exception {
		// 定义参数 begin
		String uri = url;

		SEND_XML = SEND_XML.replace("{sysAccount}", account);
		SEND_XML = SEND_XML.replace("{passWord}", password);
		SEND_XML = SEND_XML.replace("{businessType}", "1");
		SEND_XML = SEND_XML.replace("{billNoAmount}",billNoAmount);
		String xml = SEND_XML;

		String param = "method=" + URLEncoder.encode("getBillNumBySys", "utf-8");
		// XML Base64转码
		xml = getBASE64(xml);
		// XML 再encode转码
		xml = URLEncoder.encode(xml, "utf-8");
		param += "&xml=" + xml;
//		uri += "?" + param;

		String str = sendGet(uri, param);
		str = getFromBase64(str);
		EmsResponse er = JAXB.unmarshal(new StringReader(str), EmsResponse.class);
		return er;
	}
	
	public static EmsPrintDataResponse sendExpressNo(EmsXMLInfoRequest info,String account,String password,String url) throws Exception {
		//先设置账号密码
		info.setSysAccount(account);
		info.setPassWord(password);
		
		String uri = url;
		String param = "method=" + URLEncoder.encode("updatePrintDatas", "utf-8");
		StringWriter writer = new StringWriter();
		JAXB.marshal(info,writer);
		String sendXml = writer.toString();
		sendXml = getBASE64(sendXml);
		sendXml = URLEncoder.encode(sendXml, "utf-8");
		param += "&xml="+sendXml;
//		uri += "?" + param;
				
		
		String str = sendGet(uri, param);
		str = getFromBase64(str);
		EmsPrintDataResponse er = JAXB.unmarshal(new StringReader(str), EmsPrintDataResponse.class);
		return er;
//		HttpClient httpclient = new DefaultHttpClient();
//		// 创建Get方法实例
//		HttpPost httpgets = new HttpPost(uri);
//		HttpResponse response = httpclient.execute(httpgets);
//		HttpEntity entity = response.getEntity();
//		if (entity != null) {
//			InputStream instreams = entity.getContent();
//			String str = convertStreamToString(instreams);
//			str = getBASE64Decode(str);
//			httpgets.abort();
//			
//			EmsPrintDataResponse er = JAXB.unmarshal(new StringReader(str), EmsPrintDataResponse.class);
//			return er;
//		}
//		return null;
	}
	
	public static void main(String[] args) throws Exception {
		String xx = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48cmVzcG9uc2U+PHJlc3VsdD4xPC9yZXN1bHQ+PGVycm9yRGVzYz7ml6DplJnor6/kv6Hmga88L2Vycm9yRGVzYz48ZXJyb3JDb2RlPkUwMDA8L2Vycm9yQ29kZT48YXNzaWduSWRzPjxhc3NpZ25JZD48YmlsbG5vPjExMDk4Mjg4NzUxMDU8L2JpbGxubz48L2Fzc2lnbklkPjwvYXNzaWduSWRzPjwvcmVzcG9uc2U+";
//		String xxx = getBASE64Decode(xx);
//		System.out.println(xxx);
		
		String a  = getFromBase64(xx);
		System.out.println(a);
//		EmsResponse er = getExpressNo("1");
//		if(er!=null){
//			System.out.println(er.getResult());
//			System.out.println(er.getErrorDesc());
//			List<EmsAssignIds> eaList = er.getAssignIds();
//			for(EmsAssignIds eai:eaList){
//				System.out.println(eai.getAssignId().getBillno());
//			}
//		}
//		EmsXMLInfoRequest info = new EmsXMLInfoRequest();
//		
//		info.setSysAccount("44190042050000");
//		info.setPassWord("a0a475cf454cf9a06979034098167b9e");
//		info.setPrintKind("2");
//		
//		
//		List<EmsPrintDatasRequest> printDatas = new ArrayList<EmsPrintDatasRequest>();
//		EmsPrintDatasRequest pd = new EmsPrintDatasRequest();
//		EmsPrintDataRequest printData = new EmsPrintDataRequest();
//		printData.setBigAccountDataId("P123214554321");
//		printData.setBillno(er.getAssignIds().get(0).getAssignId().getBillno());
//		printData.setScontactor("派友云仓");
//		printData.setScontactor("12311223456");
//		printData.setScustMobile("");
//		printData.setScustPost("425000");
//		printData.setScustAddr("派友云仓广州仓库");
//		printData.setScustComp("派友云仓");
//		printData.setTcontactor("不知名");
//		printData.setTcustMobile("15013456689");
//		printData.setTcustTelplus("");
//		printData.setTcustPost("425000");
//		printData.setTcustAddr("广州省xx区xx路xx号");
//		printData.setTcustComp("不知名公司");
//		printData.setTcustProvince("广东省");
//		printData.setTcustCity("广州市");
//		printData.setTcustCounty("天河区");
//		printData.setWeight("1");
//		printData.setLength("2");
//		printData.setInsure("1");
//		printData.setCargoType("文件");
//		printData.setRemark("");
//		pd.setPrintData(printData);
//		printDatas.add(pd);
//		info.setPrintDatas(printDatas);
//		
//		EmsPrintDataResponse e = sendExpressNo(info);
//		System.out.println(e.getResult()+"|"+e.getErrorDesc());
		
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static String getBASE64(String str)  {
		String s = "";
		try{
			byte[] b = str.getBytes("UTF-8");
			Base64 base64 = new Base64();
			b = base64.encode(b);
			s = new String(b);
		}catch(Exception e){
			log.error("base 64 解析encode错误",e);
		}
		return s;
	}

	// 解密  
    public static String getFromBase64(String s) {  
        byte[] b = null;  
        String result = null;  
        if (s != null) {  
            BASE64Decoder decoder = new BASE64Decoder();  
            try {  
                b = decoder.decodeBuffer(s);  
                result = new String(b, "utf-8");  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }  
	public static String getBASE64Decode(String str) {
		String s = "";
		try{
			byte[] b = str.getBytes("UTF-8");
			Base64 base64 = new Base64();
			b = base64.decode(b);
			s = new String(b);
		}catch(Exception e){
			log.error("base 64 解析decode错误",e);
		}
		return s;
	}
	
	
	public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常！" , e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
